package com.yanqu.road.server.gameplayer.module.activity.tonbing;

import com.yanqu.road.entity.activity.tonbing.config.TonBingConfig;
import com.yanqu.road.entity.activity.tonbing.config.TonBingTitleConfig;
import com.yanqu.road.entity.activity.tonbing.data.TonBingUserData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.activity.tonbing.eTonBingPosition;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.task.args.activity.TonBingRedPacketValueArgs;
import com.yanqu.road.logic.bussiness.activity.TonBingActivityBusiness;
import com.yanqu.road.pb.activity.TonBingProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.EarnSpeedModule;
import com.yanqu.road.server.logic.activity.condition.tonbing.TonBingEarnSpeedEvent;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.tonbing.TonBingMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.TonBingPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TonBingModule extends GeneralModule {

    private TonBingEarnSpeedEvent earnSpeedEvent = new TonBingEarnSpeedEvent(player);

    private TonBingUserData userData;

    public TonBingModule(GamePlayer player) {
        super(player);
    }

    @Override
    public void afterLogin() {
        tonBingLogin();
    }

    @Override
    public boolean loadData() {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            userData = TonBingActivityBusiness.getTonBingUserData(config.getActivityInfo().getActivityId(), getUserId());
            if (userData == null) {
                initUserData();
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                TonBingActivityBusiness.addTonBingUserData(userData);
            } else if (userData.isUpdateOption()) {
                TonBingActivityBusiness.updateTonBingUserData(userData);
            }
        }
        return true;
    }

    /**
     * 刷新活动 || 登录
     */
    public void tonBingLogin() {
        initUserData();
        addListener();
        crossLogin();
        syncConfig();
        syncUserData();
    }

    /**
     * 同步配置
     */
    public void syncConfig() {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            TonBingProto.TonBingSyncConfigRespMsg.Builder builder = TonBingPb.parseTonBingSyncConfigRespMsg(config, player.getUserInfo().getLanguage());
            player.sendPacket(ClientProtocol.U_TON_BING_SYNC_CONFIG, builder);
        }
    }

    /**
     * 被任命了减益buff的玩家银两产出会减少
     */
    public int getPositionReduce() {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config == null) {
            return 0;
        }
        if (!ActivityMgr.activityInRewardPeriod(config.getActivityInfo())) {
            return 0;
        }
        if (userData == null || userData.getPositionMap().size() == 0) {
            return 0;
        }
        Map<Integer,Map<Integer, TonBingTitleConfig>> TonBingTitleConfigMap = config.getTitleConfigMap();
        if (!TonBingTitleConfigMap.containsKey(userData.getCampId())) {
            return 0;
        }
        Map<Integer,Integer> posMap = userData.getPositionMap();
        for(int type : posMap.keySet()){
            if (!TonBingTitleConfigMap.get(type).containsKey(posMap.get(type))) {
                return 0;
            }
        }
        int reduce = 0;
        for(int type : posMap.keySet()){
            TonBingTitleConfig TonBingTitleConfig = TonBingTitleConfigMap.get(type).get(posMap.get(type));
            if (TonBingTitleConfig.getType() != 2) {
                return 0;
            }
            // 增益buff
            if (1000 - TonBingTitleConfig.getEffect() <= 0) {
                return 0;
            }
            reduce = reduce + TonBingTitleConfig.getEffect();
        }

        return -reduce;
    }

    /**
     * 城主任命在线玩家
     */
    public void winnerAppoint(int type ,int position) {
        Map<Integer,Integer> posMap = userData.getPositionMap();
        if (!posMap.containsKey(type) || posMap.get(type) == eTonBingPosition.None.getValue()) {
            posMap.put(type,position);
            userData.setPositionMap(posMap);
        }
        player.getModule(EarnSpeedModule.class).scheduleAddSilver();
        syncUserData();
    }

    /**
     * 是否为城主
     */
    public boolean isTonBingMaster() {
        if(userData != null){
            Map<Integer,Integer> posMap = userData.getPositionMap();
            if(posMap.containsKey(0)){
                return posMap.get(0) == eTonBingPosition.Master.getValue();
            }
        }
        return false;
    }

    /**
     * 膜拜
     */
    public void worship(int type) {
        TonBingProto.TonBingCityWinnerWorshipRespMsg.Builder respMsg = TonBingProto.TonBingCityWinnerWorshipRespMsg.newBuilder();
        respMsg.setRet(0);
        TonBingConfig config = TonBingMgr.getConfig();
        //类型不对
        if(type != -1 && type != 0 && !(type >= 1 && type <= config.getCampNum())){
            respMsg.setRet(GameErrorCode.E_TON_BING_WORSHIP_DO);
            player.sendPacket(ClientProtocol.U_TON_BING_CITY_WINNER_WORSHIP, respMsg);
            return;
        }
        if (config == null || !ActivityMgr.activityInRewardPeriod(config.getActivityInfo())) {
            respMsg.setRet(GameErrorCode.E_TON_BING_NO_OPERATE_TIME);
            player.sendPacket(ClientProtocol.U_TON_BING_CITY_WINNER_WORSHIP, respMsg);
            return;
        }
        long zeroTime = DateHelper.getTodayZeroTimeStamp();
        Map<Integer, Long> wMap = userData.getWorshipTimeMap();
        if(type == -1){
            if (wMap.containsKey(type) && wMap.get(type) >= zeroTime) {
                respMsg.setRet(GameErrorCode.E_TON_BING_WORSHIP_DO);
                player.sendPacket(ClientProtocol.U_TON_BING_CITY_WINNER_WORSHIP, respMsg);
                return;
            }
        }else{
            if (wMap.containsKey(type) && wMap.get(type) >= zeroTime) {
                respMsg.setRet(GameErrorCode.E_TON_BING_WORSHIP_DO);
                player.sendPacket(ClientProtocol.U_TON_BING_CITY_WINNER_WORSHIP, respMsg);
                return;
            }
        }
        wMap.put(type,System.currentTimeMillis());
        userData.setWorshipTimeMap(wMap);
        String reward = "";
        if(type == -1){
            //排行榜的
            reward = TonBingMgr.getWorshipReward3();
        }else if(type == 0){
            //皇帝的
            reward = TonBingMgr.getWorshipReward2();
        }else{
            //城主的
            reward = TonBingMgr.getWorshipReward();
        }
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.TonBing, eLogMoneyType.TonBingWorshipReward);

        respMsg.setReward(reward);
        respMsg.setWorshipTime(wMap.get(type));
        player.sendPacket(ClientProtocol.U_TON_BING_CITY_WINNER_WORSHIP, respMsg);
        syncUserData();
    }

    /**
     * 能否购买统兵演武礼包
     */
    public boolean canBuyRechargeGift(int mallId) {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config == null) {
            return false;
        }
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return false;
        }

        long stage1BeginTime = config.getStage1TimeList().get(0).get(0);
        long zeroTimeStamp = DateHelper.getZeroTimeStamp(stage1BeginTime);
        long now = System.currentTimeMillis();
        if (now < zeroTimeStamp) {
            return false;
        }
        if (!hasCamp()) {
            return false;
        }

        return true;
    }

    /**
     * 是否有阵营
     */
    public boolean hasCamp() {
        return userData.getCampId() != 0;
    }

    /**
     * 跨服加阵营红包
     */
    public void addCrossRedPacket(GoodsInfo goodsInfo, long num) {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            log.error("ton bing activity no in time , userId {} , use red packet num {}.", player.getUserId(), num);
            return;
        }

        TonBingProto.CrossTonBingRedPacketAddReqMsg.Builder builder = TonBingProto.CrossTonBingRedPacketAddReqMsg.newBuilder();
        builder.setActivityId(config.getActivityInfo().getActivityId());
        builder.setNum((int) num);
        builder.setGoodId(goodsInfo.getGoodsId());
        player.sendPacket(CrossProtocol.C2_TON_BING_RED_PACKET_ADD, builder);
    }

    /**
     * 登录时上传数据到跨服
     */
    public void crossLogin() {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            TonBingProto.CrossTonBingLoginReqMsg.Builder builder = TonBingProto.CrossTonBingLoginReqMsg.newBuilder();
            builder.setActivityId(config.getActivityInfo().getActivityId());
            builder.setUserId(player.getUserId());
            builder.setServerId(GameServer.getInstance().getServerId());
            builder.setUnionUid(player.getUserInfo().getUnionUid());
            builder.addAllPatronsList(TonBingPb.parseTonBingPatronsListMsg(player.getModule(PatronsModule.class).getUserPatronsList()));
            builder.setUserBaseInfo(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
            builder.addAllSoldierAddition(player.getModule(PatronsModule.class).getTonBingSoldierAddition());
            player.sendPacket(CrossProtocol.C2_CROSS_TON_BING_LOGIN, builder);
        }
    }

    /**
     * 添加报名期赚速变化监听器
     */
    public void addListener() {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config != null && System.currentTimeMillis() < config.getJoinTimeList().get(1)) {
            earnSpeedEvent.addTrigger();
        }
    }

    /**
     * 初始化玩家数据
     */
    private synchronized void initUserData() {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            if (userData == null || config.getActivityInfo().getActivityId() != userData.getActivityId()) {
                TonBingUserData tempUserData = new TonBingUserData();
                tempUserData.setActivityId(config.getActivityInfo().getActivityId());
                tempUserData.setUserId(getUserId());
                tempUserData.setWorshipTimeMap(new ConcurrentHashMap<>());
                tempUserData.setPositionMap(new ConcurrentHashMap<>());
                tempUserData.setZhanGong(0);
                tempUserData.setSkinExchangeMap(new ConcurrentHashMap<>());
                tempUserData.setInsertOption();
                userData = tempUserData;
            }
        }
    }

    // 同步玩家数据
    public void syncUserData() {
        // 上跨服吧，还有一些跨服数据
        TonBingConfig config = TonBingMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            TonBingProto.TonBingUserDataSyncMsg.Builder respMsg = TonBingProto.TonBingUserDataSyncMsg.newBuilder();
            respMsg.setActivityId(userData.getActivityId());
            //下面那两个字段不知道什么鸟用了，留着过年吧
            respMsg.setWorshipTime(0);
            respMsg.setPositionId(0);
            respMsg.setCampId(userData.getCampId());
            respMsg.setZhanGong(userData.getZhanGong());
            respMsg.setWinnerId(0L);
            for (Map.Entry<Integer, Integer> entry : userData.getSkinExchangeMap().entrySet()) {
                TonBingProto.TonBingSkinExchangeTemp.Builder temp = TonBingProto.TonBingSkinExchangeTemp.newBuilder();
                temp.setSkinId(entry.getKey());
                temp.setCount(entry.getValue());
                respMsg.addSkinExchange(temp);
            }
            //todo-xx 赋值 同步的要赋值
            respMsg.setMatchId(0L);
            respMsg.setWarType(0L);
            Map<Integer, Long> wMap = userData.getWorshipTimeMap();
            for(Integer wType : wMap.keySet()){
                TonBingProto.TonBingWorshipTempMsg.Builder worshipMsg = TonBingProto.TonBingWorshipTempMsg.newBuilder();
                worshipMsg.setType(wType);
                worshipMsg.setWorshipTime(wMap.get(wType));
                respMsg.addWorships(worshipMsg);
            }
            player.sendPacket(CrossProtocol.C2_TON_BING_SYNC_USER_DATA, respMsg);
        }
    }

    /**
     * 加阵营红包成就进度
     */
    public void notifyRedPackValue(int activityId, long value) {
        if (userData.getActivityId() == activityId) {
            player.notifyListenerAndSync(eGamePlayerEventType.TonBingCampBoxScore.getValue(), new TonBingRedPacketValueArgs(activityId,value));
        }
    }

    /**
     * 更新用户数据
     */
    public void updateUserData(TonBingProto.CrossTonBingSyncUserDataMsg reqMsg) {
        TonBingConfig config = TonBingMgr.getConfig();
        if (config == null) {
            return;
        }
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        if (userData == null) {
            return;
        }
        // 其他需要同步到游戏服的数据在这处理
        userData.setCampId(reqMsg.getCampId());
        userData.setZhanGong(reqMsg.getZhanGong());
        // 同步玩家数据
        syncUserData();
        if(reqMsg.getSendLogin()){
            crossLogin();
        }
    }

    /**
     * 兑换皮肤
     *
     * @param skinId 皮肤id
     */
    public int exchangeSkin(int skinId) {
        if (userData == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        TonBingConfig config = TonBingMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        TonBingProto.TonBingExchangeSkinRespMsg.Builder respMsg = TonBingProto.TonBingExchangeSkinRespMsg.newBuilder();
        String skinsExchangeParam = config.getSkinsExchangeParam();
        String[] skinExchanges = skinsExchangeParam.split("\\|");
        for (String skinExchange : skinExchanges) {
            String[] item = skinExchange.split(",");
            // 服装ID#兑换所需战功值
            String skinStr = item[0];
            // 服装id
            String[] split = skinStr.split("#");
            int configSkinId = Integer.parseInt(split[0]);
            if (configSkinId != skinId) {
                continue;
            }
            // 兑换所需战功值
            long needZhanGong = Long.parseLong(split[1]);
            // 限购数量
            int exchangeLimit = Integer.parseInt(item[1]);
            // 兑换道具=兑换道具数量
            String cost = item[2];
            // 判断战功是否足够
            if (userData.getZhanGong() < needZhanGong) {
                return GameErrorCode.E_TON_BING_ZHANGONG_NOT_ENOUGH;
            }
            Map<Integer, Integer> skinExchangeMap = userData.getSkinExchangeMap();
            int count = skinExchangeMap.getOrDefault(skinId, 0);
            // 判断是否兑换已达上限
            if (count >= exchangeLimit) {
                return GameErrorCode.E_TON_BING_ZHANGONG_EXCHANGE_LIMIT;
            }
            // 消耗道具兑换
            if (!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(cost), eLogMoneyType.TonBing, eLogMoneyType.TonBingExchangeSkinCost)) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
            // 记录
            skinExchangeMap.put(skinId, count + 1);
            userData.setSkinExchangeMap(skinExchangeMap);
            // 获得道具
            Property property = new Property(skinId, BigInteger.ONE);
            player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.TonBing, eLogMoneyType.TonBingExchangeSkinGet);
            respMsg.setReward(PropertyHelper.parsePropertyToString(property));
        }
        respMsg.setRet(0);
        for (Map.Entry<Integer, Integer> entry : userData.getSkinExchangeMap().entrySet()) {
            TonBingProto.TonBingSkinExchangeTemp.Builder temp = TonBingProto.TonBingSkinExchangeTemp.newBuilder();
            temp.setSkinId(entry.getKey());
            temp.setCount(entry.getValue());
            respMsg.addSkinExchange(temp);
        }
        player.sendPacket(ClientProtocol.U_TON_BING_EXCHANGE_SKIN, respMsg);
        return 0;
    }

}
